//
//  MainViewController.m
//  TomCat
//
//  Created by cocoazxj@163.com on 15/3/23.
//  Copyright (c) 2015年 handcool. All rights reserved.
//

#import "MainViewController.h"

@interface MainViewController ()
@property (nonatomic, strong) IBOutlet UIImageView *iv_show;
@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)drinkButtonClicked:(id)sender
{
//    [self animationTom:@"drink" pictureCount:81];
    [self annimationTom:@"Drink"];
}

// 初级方法
- (void)animationTom:(NSString *)name pictureCount:(int)count
{
    if ([self.iv_show isAnimating])
    {
        return ;
    }
    NSMutableArray *picArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < count; i++)
    {
        NSString *pictureName = [NSString stringWithFormat:@"%@_%02d",name,i];
        NSString *path = [[NSBundle mainBundle] pathForResource:pictureName ofType:@".jpg"];
        UIImage *image = [UIImage imageWithContentsOfFile:path];
        [picArray addObject:image];
    }
    
    [self.iv_show setAnimationImages:picArray];
    [self.iv_show setAnimationDuration:picArray.count*0.075];
    [self.iv_show setAnimationRepeatCount:1];
    
    [self.iv_show startAnimating];
    
    [self.iv_show performSelector:@selector(setAnimationImages:) withObject:nil afterDelay:picArray.count*0.075 + 0.05];
}

// 高级方法
// 图片放在没有放在mainBundle中，而是新建了一个文件夹。游戏中开发这样使用，避免重名。
- (void)annimationTom:(NSString *)dirName;
{
    if ([self.iv_show isAnimating])
    {
        return ;
    }
    NSMutableArray *picArray = [NSMutableArray array];
    
    // 获取文件目录
    NSString *path = [[[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Animation"] stringByAppendingPathComponent:dirName];
    
    // 读取目录中所有文件的名字
    NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];
    NSLog(@"%@", files);
    
    for (NSString *fileName in files)
    {
        NSString *filePath = [NSString stringWithFormat:@"%@/%@",path,fileName];
        UIImage *image = [UIImage imageWithContentsOfFile:filePath];
        [picArray addObject:image];
    }
    [self.iv_show setAnimationImages:picArray];
    [self.iv_show setAnimationDuration:picArray.count * 0.075];
    [self.iv_show setAnimationRepeatCount:1];
    
    [self.iv_show startAnimating];
    [self.iv_show performSelector:@selector(setAnimationImages:) withObject:nil afterDelay:self.iv_show.animationDuration];
}

@end
